const exec = require('child_process').exec;
const rm = require('rimraf').sync;
const inquirer = require('inquirer');
const axios = require('axios');

class Utils {
    /**
   * 删除文件
   * @param path
   */
  remove(path) {
    return new Promise((resolve, reject) => {
      rm(path, err => {
        if (err) {
          reject({ type: 'remove', msg: err });
        } else {
          resolve();
        }
      });
    });
  }

  /**
   * 执行 Shell 命令
   * @param cmd
   */
  shell(cmd) {
    return new Promise((resolve, reject) => {
      exec(cmd, (err, stdout, stderr) => {
        if (err) {
          reject({ type: 'shell', msg: stdout + stderr });
        } else {
          resolve(stdout);
        }
      });
    });
  }

  /**
   * 通过 inquirer 询问用户
   * @param config
   */
  ask(config) {
    return new Promise((resolve, reject) => {
      inquirer.prompt(config).then(answers => {
        resolve(answers);
      });
    });
  }

  /**
   * ajax 请求接口
   * @param options
   */
  request(options) {
    return new Promise((resolve, reject) => {
      axios(options).then((response) => {
        resolve(response);
      }).catch(err => {
        reject({ type: 'ajax请求', msg: err });
      });
    });
  }
}

module.exports = new Utils();